package com.google.code.UtopiaXml;

import java.util.Objects;

/**
 * Property that represents property of a class(attribute) of given Type.
 *
 * @author Michael Simacek
 */
public class SingleProperty implements Property {

    private Type type;
    private String name;

    /**
     * Constructs property of given name and type
     *
     * @param type property type
     * @param name property name
     */
    public SingleProperty(Type type, String name) {
        if (type == null) {
            throw new IllegalArgumentException("type is null");
        }
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        this.type = type;
        this.name = CodeBuilder.toLowerCamelCase(name);
    }

    @Override
    public void generateDeclaration(CodeBuilder cb) {
        if (type.getDefaultValue() == null) {
            cb.appendLine("private " + type.getTypeName() + " " + name + ";");
        } else {
            cb.appendLine("private " + type.getTypeName() + " " + name + " = " + type.getDefaultValue() + ";");
        }
        cb.addImport(type.getImport());
    }

    @Override
    public void generateAccessors(CodeBuilder cb) {
        String upName = CodeBuilder.toUpperCamelCase(name);
        cb.appendLine("public " + type.getTypeName() + " get" + upName + "(){");
        cb.appendLine("return " + name + ";");
        cb.appendLine("}");
        cb.newLine();
        cb.appendLine("public void set" + upName + "(" + type.getTypeName() + " " + name + "){");
        cb.appendLine("this." + name + " = " + name + ";");
        cb.appendLine("}");
        cb.newLine();
        cb.addImport(type.getImport());
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Type getType() {
        return type;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 89 * hash + Objects.hashCode(this.name);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final SingleProperty other = (SingleProperty) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return true;
    }
}
